<template>
  <base-window :title="$t('task.detail.components.cancelDescription')" :show.sync="visible" class-name="task-cancel-dialog">
    <div class="base-modal-content">
      <template v-if="cancelModal.showWithPart">
        <div class="form-item">
          <label :class="{'form-item-required': !cancelModal.isGoBack && cancelModal.isRequired}">
            <span class="form-item-required">*</span>
            {{ showWithPartMsg }}
          </label>
          <div class="form-item-control">
            <el-radio-group v-model="cancelModal.isGoBack">
              <el-radio label="1">{{$t('common.base.yes')}}</el-radio>
              <el-radio label="0">{{$t('common.base.no')}}</el-radio>
            </el-radio-group>
            <span class="form-item-required" v-if="!cancelModal.isGoBack && cancelModal.isRequired">{{$t('common.base.required')}}</span>
          </div>
        </div>
        <p class="tips">{{$t('task.tip.cancelTaskTip1')}}</p>
      </template>
      <template v-else-if="cancelModal.errorWithPart">
        <p>{{$t('task.tip.cancelTaskTip2')}}</p>
      </template>

      <div class="task-detail-view-panel">
        <div class="task-flex task-ai">
          <span v-if="required" class="task-cef task-font16 task-detail-view-panel-icon">*</span><span>{{$t('task.cancelReason')}}：</span>
          <el-select v-model="checkBack" clearable :placeholder="`${requiredPlaceholder} ${$t('task.tip.cancelTaskTip3')}`" class="task-w70">
            <el-option
              v-for="item in backList"
              :key="item"
              :label="item"
              :value="item"
            >
            </el-option>
          </el-select>
          <span class="task-font12 task-c13 task-ml12 task-pointer" v-if="systemAdmin" @click="jump()">{{$t('task.goSetReason')}}</span>
        </div>
        <!--  -->
        <div class="task-flex task-mt12">
          <div class="task-font14">{{$t('task.detailReason')}}：</div>
          <textarea class="base-modal-textarea" v-model="cancelModal.reason" :placeholder="$t('task.tip.cancelTaskTip4')" rows="3" maxlength="500" />
        </div>

        <template v-if="isProjectTask">
          <div class="tag-mess">
            <el-tag type="warning">{{ $t('common.projectManage.cancelText1') }}</el-tag>
          </div>
        </template>
      </div>
     
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button @click="visible = false">{{$t('common.base.cancel')}}</el-button>
      <el-button type="primary" @click="submit" :disabled="pending">{{$t('common.base.makeSure')}}</el-button>
    </div>
  </base-window>
</template>

<script>
/* api */
import * as TaskApi from '@src/api/TaskApi.ts';
import { openAccurateTab } from '@src/util/platform'
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'

export default {
  name: 'cancel-task-dialog',
  props: {
    taskId: {
      type: String,
      default: '',
    },
    cardInfo: {
      type: Array,
      default: () => ([])
    },
    backList: {
      type: Array,
      default: () => {[]}
    },
    systemAdmin: {
      type: Boolean | String,
      default: ''
    },
    required: {
      type: Boolean
    },
    requiredPlaceholder: {
      type: String,
      default: ''
    },
    // 是否是工单任务类型的工单
    isProjectTask: {
      type: Boolean | String,
      default: '',
    }
  },
  data() {
    return {
      visible: false,
      pending: false,
      cancelModal: this.buildModalParams(),
      checkBack: ''
    }
  },
  computed: {
    /**
    * @description 备件清单附加组件
    */
    sparepartCard() {
      return this.cardInfo.find(card => card.specialfrom == '备件清单') || {};
    },
    showWithPartMsg() {
      let isHasPartCard = this.sparepartCard.cardId ? this.$t('task.detail.components.orSparePartList') : '';
      return this.$t('task.tip.cancelTaskTip5', {data: isHasPartCard});
    }
  },
  methods: {
    jump() {
      openAccurateTab({
        type: PageRoutesTypeEnum.PageTaskSetting,
      })

    },
    buildParams() {
      let { showWithPart, isGoBack, reason } = this.cancelModal;

      let content = {updateType: 'tRecord', updateContent: reason};
      let task = {id: this.taskId};

      if (showWithPart) content.isGoBack = isGoBack;

      return {
        content,
        task
      }
    },
    buildModalParams() {
      return {
        showWithPart: false,
        errorWithPart: false,
        isRequired: false,
        reason: '',
        isGoback: ''
      }
    },
    async openDialog() {
      if (this.pending) return;
      this.pending = true;

      // 重置
      this.cancelModal = this.buildModalParams();

      try {
        // 需要判断工单是否曾回退，而且在最后一次完成时是否使用了备件
        const res = await TaskApi.finishedWithPart({ taskId: this.taskId });
        if (res.success) {
          this.cancelModal.showWithPart = res.result;
        } else {
          this.cancelModal.errorWithPart = true;
        }

        this.pending = false;
        this.visible = true;

      } catch (e) {
        console.error('cancelTask error', e);
      }
    },
    async submit() {
      let { showWithPart, isGoBack, reason } = this.cancelModal;

      const {checkBack, required} = this
      if (!checkBack && required) {
        this.$platform.alert(this.$t('task.tip.cancelTaskTip3'));
        return
      }
      
      // 工单如果使用了备件，则"是否做退回处理"必选
      if (showWithPart && !isGoBack) return this.cancelModal.isRequired = true;

      // if (!reason.trim()) return this.$platform.alert('请填写取消说明');


      this.pending = true;


      if (this.isProjectTask) {
        let taskTipMsg = this.$t('common.projectManage.cancelTip1');
        // 工单类型的任务删除弹窗提示
        const msgResult = await this.$platform.confirm(taskTipMsg);
        if (!msgResult) return this.pending = false;
      }

      // 先判断是否需要高级审批
      let approveParams = {
        taskId: this.taskId,
        action: 'off',
        offInfo: {
          taskId: this.taskId,
          reason: this.cancelModal.reason,
          isGoBack: this.cancelModal?.isGoBack ?? '',
          customReason: checkBack,
        }
      }

      const approveResult = await TaskApi.checkNeedVipApprove(approveParams);
      if (approveResult?.success && approveResult?.result?.needVipApprove) {
        this.$emit('proposeApprove', approveResult?.result ?? {});
        this.visible = false;
        this.pending = false;
        return
      }

      // 取消是否需要审批
      const result = await TaskApi.offApproveCheck(this.buildParams());
      // TODO 需要审批判断改成errorCode
      if (!result.succ && Number(result.errorCode) == 10003) {
        // 添加reason字段传给后端
        result.data ? result.data.reason = reason : null
        this.$emit('proposeApprove', {data: result.data, customReason: checkBack});
        this.visible = false;
        this.pending = false;
        return;
      }
      // 返回错误提示
      if (!result.succ) {
        this.pending = false;
        return this.$platform.alert(result.message);
      }

      const params = { taskId: this.taskId, reason, customReason: checkBack };
      if (showWithPart) params.isGoBack = isGoBack;

      TaskApi.cancelTask(params).then(res => {
        if (res.success) {
          let fromId = window.frameElement.getAttribute('fromid');
          // this.$platform.refreshTab(fromId);

          window.location.reload();
        } else {
          this.$platform.alert(res.message);
          this.pending = false;
        }
      }).catch(err => {
        this.pending = false;
      })
    },

  }
}
</script>

<style lang="scss">
.task-cancel-dialog {
  min-width: 620px !important;
  min-height: 320px !important;

  .form-item {
    margin-bottom: 6px;

    & > label {
      width: auto !important;
      padding-left: 0;
    }

    .form-item-control {
      label {
        width: auto !important;
        display: inline-block;
      }

      .el-radio-group {
        vertical-align: baseline;
      }
    }
  }

  .tag-mess {
    margin: 10px 0 0 70px;
  }
}
</style>
